// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.material.service.impl;

import cn.hutool.core.date.DateUtil;
import com.liuxinlong.common.AosException;
import com.liuxinlong.common.ExcelData;
import com.liuxinlong.common.ExcelImportCallBack;
import com.liuxinlong.common.ExcelImportService;
import com.liuxinlong.common.ImportResp;
import com.liuxinlong.common.RowError;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.RegionConstants;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.MaterialResumeTypeEnum;
import com.liuxinlong.enums.ModifyTypeEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.MaterialDao;
import com.liuxinlong.modules.dao.MaterialResumeDao;
import com.liuxinlong.modules.dao.MocDetailDao;
import com.liuxinlong.modules.dao.MocRecordDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.entity.MaterialResume;
import com.liuxinlong.modules.entity.MocDetail;
import com.liuxinlong.modules.entity.MocRecord;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.material.dto.MaterialStatusImportDto;
import com.liuxinlong.modules.material.service.MaterialStatusService;
import com.liuxinlong.utils.ExcelUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 物料状态变更service实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年2月17日
 */
@Service
@Slf4j
public class MaterialStatusServiceImpl implements MaterialStatusService {

    @Autowired
    private MaterialDao materialDao;

    @Autowired
    private MocRecordDao mocRecordDao;

    @Autowired
    private MocDetailDao mocDetailDao;

    @Autowired
    private ExcelImportService excelImportService;

    @Autowired
    private MaterialResumeDao materialResumeDao;

    @Autowired
    private UserDao userDao;

    @Override
    public List<Map<String, Object>> pageMaterialStatusRecord(Map<String, Object> queryParam) {
        queryParam.put("changeType", MaterialResumeTypeEnum.STATUS_CHANGE.getValue());
        List<String> idList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(queryParam.get("materialNo"))) {
            queryParam.put("keyword", queryParam.get("materialNo"));
            List<MocDetail> mocDetails = mocDetailDao.pageDetailList(queryParam);
            idList = mocDetails.stream().map(MocDetail::getRecordId).collect(Collectors.toList());
            if (ObjectUtils.isEmpty(idList)) {
                return new ArrayList<>();
            }
        }
        queryParam.put("idList", idList);

        List<MocRecord> originList = mocRecordDao.pageRecordList(queryParam);
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        int sort = (int) queryParam.get("startNum") + 1;
        for (MocRecord record : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(record);
            map.put("sort", sort);
            map.put("enterUserName", userMap.containsKey(record.getEnterUser()) ? userMap.get(record.getEnterUser()).get("name") : "");
            map.put("targetStatus", "A");
            resultList.add(map);
            sort++;
        }
        return resultList;
    }

    @Override
    public int getStatusRecordCount(Map<String, Object> queryParam) {
        queryParam.put("changeType", 3);
        List<String> idList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(queryParam.get("materialNo"))) {
            queryParam.put("keyword", queryParam.get("materialNo"));
            List<MocDetail> mocDetails = mocDetailDao.pageDetailList(queryParam);
            idList = mocDetails.stream().map(MocDetail::getRecordId).collect(Collectors.toList());
            if (ObjectUtils.isEmpty(idList)) {
                return 0;
            }
        }
        queryParam.put("idList", idList);
        return mocRecordDao.getRecordCount(queryParam);
    }

    @Override
    @Transactional
    public void batchUpdateMaterialStatus(String targetIds, String region, String targetStatus) {
        // TODO region改为数据库获取或枚举类
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(targetIds);
        List<String> targetIdList = Arrays.asList(m.replaceAll("").split(","));
        materialDao.batchUpdateMaterialStatus(targetIdList, targetStatus);
        Date currentDate = new Date();
        SimpleDateFormat format = new SimpleDateFormat(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        SimpleDateFormat titleFormat = new SimpleDateFormat(TimeFormatConstants.YYYYMMDD);
        MocRecord mocRecord = new MocRecord();
        String recordId = SnowFlake.nextIdStr();
        mocRecord.setId(recordId);
        mocRecord.setChangeType(3);
        String changeTime = format.format(currentDate);
        mocRecord.setChangeTime(changeTime);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        mocRecord.setEnterUser(currentUser.getId());
        mocRecord.setReason("物料状态变更-" + targetStatus);
        mocRecord.setTitle("物料状态变更-" + targetStatus + "-" + titleFormat.format(currentDate));
        mocRecordDao.insert(mocRecord);
        List<MocDetail> mdList = new ArrayList<>(targetIdList.size());
        List<MaterialResume> mrList = new ArrayList<>(targetIdList.size());
        for (String materialId : targetIdList) {
            String id = SnowFlake.nextIdStr();
            MocDetail mocDetail = createMD(id, recordId, materialId, targetStatus, region);
            mdList.add(mocDetail);
            MaterialResume mr = createMR(mocDetail, currentUser.getId(), changeTime);
            mrList.add(mr);
        }
        mocDetailDao.insertBatch(mdList);
        materialResumeDao.batchAddResume(mrList);
    }

    @Override
    @Transactional
    public void deleteMaterialStatus(String id) {
        MocRecord mr = mocRecordDao.selectById(id);
        if (ObjectUtils.isEmpty(mr)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除失败，变更记录不存在！");
        }
        User current = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (!StringUtils.equals(current.getId(), "1") && !StringUtils.equals(mr.getEnterUser(), current.getId())) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除失败，不可删除非本用户操作数据！");
        }
        mocRecordDao.deleteById(id);
        mocDetailDao.deleteByRecordId(id);
    }

    @Override
    @Transactional
    public ImportResp batchAddDetail(List<MaterialStatusImportDto> dataList) {
        List<String> materialList = dataList.stream().map(MaterialStatusImportDto::getMaterial).collect(Collectors.toList());
        List<MocDetail> mdOldList = mocDetailDao.getDetailsByMaterials(materialList);
        Map<String, MocDetail> mdOldMap = new HashMap<>();
        for (MocDetail md : mdOldList) {
            String uniqueId = md.getMaterial() + "#" + md.getRegion() + "#" + md.getNewValue() + "#" + (StringUtils.equals(md.getParam(), "状态") ? ModifyTypeEnum.STATUS_CHANGE.getValue() : ModifyTypeEnum.PARAM_CHANGE.getValue());
            mdOldMap.put(uniqueId, md);
        }
        List<Map> failedList = new ArrayList<>();
        Date currentDate = new Date();
        SimpleDateFormat format = new SimpleDateFormat(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        SimpleDateFormat titleFormat = new SimpleDateFormat(TimeFormatConstants.YYYYMMDD);

        Set<String> changeTimeSet = dataList.stream().filter(a -> StringUtils.isNotEmpty(a.getChangeTime()))
                .map(MaterialStatusImportDto::getChangeTime).collect(Collectors.toSet());
        Map<String, String> recordMap = new HashMap<>();
        recordMap.put("", SnowFlake.nextIdStr());
        if (!changeTimeSet.isEmpty()) {
            for (String changeTime : changeTimeSet) {
                recordMap.put(changeTime, SnowFlake.nextIdStr());
            }
        }
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);

        // 动态匹配region
        List<MocDetail> mdList = new ArrayList<>(dataList.size());
        List<MaterialResume> mrList = new ArrayList<>(dataList.size());
        int count = 0;
        int sort = 1;
        for (MaterialStatusImportDto materialStatusImportDto : dataList) {
            String changeTime = materialStatusImportDto.getChangeTime();
            if (StringUtils.isEmpty(changeTime)) {
                changeTime = "";
                count++;
            }
            String recordId = recordMap.get(changeTime);
            if (StringUtils.isNotEmpty(materialStatusImportDto.getRegionOne())) {
                String uniqueId = materialStatusImportDto.getMaterial() + "#" + RegionConstants.WPCNJ + "#" + materialStatusImportDto.getRegionOne() + "#" + ModifyTypeEnum.STATUS_CHANGE.getValue();
                if (mdOldMap.containsKey(uniqueId)) {
                    Map map = ObjectUtils.object2Map(materialStatusImportDto);
                    map.put("sort", sort);
                    map.put("message", "已存在状态变更记录");
                    sort++;
                    failedList.add(map);
                    continue;
                }
                String id = SnowFlake.nextIdStr();
                MocDetail mocDetail = createMD(id, recordId, materialStatusImportDto.getMaterial(), materialStatusImportDto.getRegionOne(), RegionConstants.WPCNJ);
                mdList.add(mocDetail);
                MaterialResume mr = createMR(mocDetail,currentUser.getId(), materialStatusImportDto.getChangeTime());
                mrList.add(mr);
            }
            if (StringUtils.isNotEmpty(materialStatusImportDto.getRegionTwo())) {
                String uniqueId = materialStatusImportDto.getMaterial() + "#" + RegionConstants.WSCNJ + "#" + materialStatusImportDto.getRegionOne() + "#" + ModifyTypeEnum.STATUS_CHANGE.getValue();
                if (mdOldMap.containsKey(uniqueId)) {
                    Map map = ObjectUtils.object2Map(materialStatusImportDto);
                    map.put("sort", sort);
                    map.put("message", "已存在状态变更记录");
                    sort++;
                    failedList.add(map);
                    continue;
                }
                String id = SnowFlake.nextIdStr();
                MocDetail mocDetail = createMD(id, recordId, materialStatusImportDto.getMaterial(),materialStatusImportDto.getRegionTwo(), RegionConstants.WSCNJ);
                mdList.add(mocDetail);
                MaterialResume mr = createMR(mocDetail,currentUser.getId(), materialStatusImportDto.getChangeTime());
                mrList.add(mr);
            }
            if (StringUtils.isNotEmpty(materialStatusImportDto.getRegionThree())) {
                String uniqueId = materialStatusImportDto.getMaterial() + "#" + RegionConstants.SWTNJ + "#" + materialStatusImportDto.getRegionOne() + "#" + ModifyTypeEnum.STATUS_CHANGE.getValue();
                if (mdOldMap.containsKey(uniqueId)) {
                    Map map = ObjectUtils.object2Map(materialStatusImportDto);
                    map.put("sort", sort);
                    map.put("message", "已存在状态变更记录");
                    sort++;
                    failedList.add(map);
                    continue;
                }
                String id = SnowFlake.nextIdStr();
                MocDetail mocDetail = createMD(id, recordId, materialStatusImportDto.getMaterial(), materialStatusImportDto.getRegionThree(), RegionConstants.SWTNJ);
                mdList.add(mocDetail);
                MaterialResume mr = createMR(mocDetail,currentUser.getId(), materialStatusImportDto.getChangeTime());
                mrList.add(mr);
            }
        }
        // 添加变更记录
        List<MocRecord> mocRecordList = new ArrayList<>(recordMap.size());
        for (String changeTime : recordMap.keySet()) {
            if (StringUtils.isEmpty(changeTime) && count == 0) {
                continue;
            }
            MocRecord mocRecord = new MocRecord();
            String recordId = recordMap.get(changeTime);
            mocRecord.setId(recordId);
            mocRecord.setChangeType(3);
            mocRecord.setChangeTime(StringUtils.isNotEmpty(changeTime) ? changeTime : format.format(currentDate));
            mocRecord.setEnterUser(currentUser.getId());
            mocRecord.setReason("物料状态变更");
            mocRecord.setTitle("物料状态变更" + "-" + titleFormat.format(StringUtils.isNotEmpty(changeTime) ? DateUtil.parse(changeTime) : currentDate));
            mocRecordList.add(mocRecord);
        }
        ImportResp resp = new ImportResp();
        if (ObjectUtils.isEmpty(mocRecordList)) {
            return resp;
        }
        mocRecordDao.insertBatch(mocRecordList);
        // 添加变更详情
        List<MocDetail> mdWithoutDupList = mdList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getMaterial() + "#" + o.getRegion() + "#" + o.getNewValue()))), ArrayList::new));
        if (!ObjectUtils.isEmpty(mdWithoutDupList)) {
            mocDetailDao.insertBatch(mdWithoutDupList);
        }
        List<MaterialResume> mrWithoutDupList = mrList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getMaterialNo() + "#" + o.getRegion() + "#" + o.getOperateType() + "#" + o.getContent()))), ArrayList::new));
        if (!ObjectUtils.isEmpty(mrWithoutDupList)) {
            materialResumeDao.insertBatch(mrWithoutDupList);
        }
        for (MocRecord mr : mocRecordList) {
            Map<String, Object> queryParam = new HashMap<>();
            queryParam.put("recordId", mr.getId());
            int existDetails = mocDetailDao.getDetailCount(queryParam);
            if (existDetails == 0) {
                mocRecordDao.deleteById(mr.getId());
            }
        }
        resp.setFailedList(failedList);
        resp.setRetCode(failedList.size() > 0 ?
                ReturnCodes.HTTP_IMPORT_PART_FAIL.getRetCode() : ReturnCodes.HTTP_SUCCESS.getRetCode());
        resp.setRetMessage(failedList.size() > 0 ? "导入状态变更信息部分成功" : "导入状态变更信息成功");
        return resp;
    }

    @Override
    public void exportMaterialStatus(String startTime, HttpServletResponse response) {
        ExcelData data = new ExcelData();
        data.setFileName("物料状态变更导出结果excel.xlsx");
        List<MaterialStatusImportDto> changeList = mocDetailDao.getMaterialStatusChanges(startTime);
        String[] head = {"物料号", "WPCNJ", "WSCNJ", "SWTNJ", "变更时间"};
        data.setHead(head);
        String[][] dataList = new String[changeList.size()][head.length];
        int index = 0;
        for (MaterialStatusImportDto item : changeList) {
            dataList[index][0] = item.getMaterial();
            dataList[index][1] = item.getRegionOne();
            dataList[index][2] = item.getRegionTwo();
            dataList[index][3] = item.getRegionThree();
            dataList[index][4] = item.getChangeTime().substring(0, 10);
            index++;
        }
        data.setData(Arrays.asList(dataList));
        ExcelUtils.exportExcel(response, data);
    }

    @Override
    public ImportResp batchAddDetail(List<MaterialStatusImportDto> dataList, String recordId) {
        List<String> materialList = dataList.stream().map(MaterialStatusImportDto::getMaterial).collect(Collectors.toList());
        List<MocDetail> mdOldList = mocDetailDao.getDetailsByMaterials(materialList);
        Map<String, MocDetail> mdOldMap = new HashMap<>();
        for (MocDetail md : mdOldList) {
            String uniqueId = md.getMaterial() + "#" + md.getRegion() + "#" + md.getNewValue() + "#" + (StringUtils.equals(md.getParam(), "状态") ? ModifyTypeEnum.STATUS_CHANGE.getValue() : ModifyTypeEnum.PARAM_CHANGE.getValue());
            mdOldMap.put(uniqueId, md);
        }
        List<Map> failedList = new ArrayList<>();

        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);

        // 动态匹配region
        List<MocDetail> mdList = new ArrayList<>(dataList.size());
        List<MaterialResume> mrList = new ArrayList<>(dataList.size());
        int sort = 1;
        for (MaterialStatusImportDto materialStatusImportDto : dataList) {
            if (StringUtils.isNotEmpty(materialStatusImportDto.getRegionOne())) {
                String uniqueId = materialStatusImportDto.getMaterial() + "#" + RegionConstants.WPCNJ + "#" + materialStatusImportDto.getRegionOne() + "#" + ModifyTypeEnum.STATUS_CHANGE.getValue();
                if (mdOldMap.containsKey(uniqueId)) {
                    Map map = ObjectUtils.object2Map(materialStatusImportDto);
                    map.put("sort", sort);
                    map.put("message", "已存在状态变更记录");
                    sort++;
                    failedList.add(map);
                    continue;
                }
                String id = SnowFlake.nextIdStr();
                MocDetail mocDetail = createMD(id, recordId, materialStatusImportDto.getMaterial(), materialStatusImportDto.getRegionOne(), RegionConstants.WPCNJ);
                mdList.add(mocDetail);
                MaterialResume mr = createMR(mocDetail,currentUser.getId(), materialStatusImportDto.getChangeTime());
                mrList.add(mr);
            }
            if (StringUtils.isNotEmpty(materialStatusImportDto.getRegionTwo())) {
                String uniqueId = materialStatusImportDto.getMaterial() + "#" + RegionConstants.WSCNJ + "#" + materialStatusImportDto.getRegionTwo() + "#" + ModifyTypeEnum.STATUS_CHANGE.getValue();
                if (mdOldMap.containsKey(uniqueId)) {
                    Map map = ObjectUtils.object2Map(materialStatusImportDto);
                    map.put("sort", sort);
                    map.put("message", "已存在状态变更记录");
                    sort++;
                    failedList.add(map);
                    continue;
                }
                String id = SnowFlake.nextIdStr();
                MocDetail mocDetail = createMD(id, recordId, materialStatusImportDto.getMaterial(),materialStatusImportDto.getRegionTwo(), RegionConstants.WSCNJ);
                mdList.add(mocDetail);
                MaterialResume mr = createMR(mocDetail,currentUser.getId(), materialStatusImportDto.getChangeTime());
                mrList.add(mr);
            }
            if (StringUtils.isNotEmpty(materialStatusImportDto.getRegionThree())) {
                String uniqueId = materialStatusImportDto.getMaterial() + "#" + RegionConstants.SWTNJ + "#" + materialStatusImportDto.getRegionThree() + "#" + ModifyTypeEnum.STATUS_CHANGE.getValue();
                if (mdOldMap.containsKey(uniqueId)) {
                    Map map = ObjectUtils.object2Map(materialStatusImportDto);
                    map.put("sort", sort);
                    map.put("message", "已存在状态变更记录");
                    sort++;
                    failedList.add(map);
                    continue;
                }
                String id = SnowFlake.nextIdStr();
                MocDetail mocDetail = createMD(id, recordId, materialStatusImportDto.getMaterial(), materialStatusImportDto.getRegionThree(), RegionConstants.SWTNJ);
                mdList.add(mocDetail);
                MaterialResume mr = createMR(mocDetail,currentUser.getId(), materialStatusImportDto.getChangeTime());
                mrList.add(mr);
            }
        }
        ImportResp resp = new ImportResp();
        // 添加变更详情
        List<MocDetail> mdWithoutDupList = mdList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getMaterial() + "#" + o.getRegion() + "#" + o.getNewValue()))), ArrayList::new));
        if (!ObjectUtils.isEmpty(mdWithoutDupList)) {
            mocDetailDao.insertBatch(mdWithoutDupList);
        }
        List<MaterialResume> mrWithoutDupList = mrList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getMaterialNo() + "#" + o.getRegion() + "#" + o.getOperateType() + "#" + o.getContent()))), ArrayList::new));
        if (!ObjectUtils.isEmpty(mrWithoutDupList)) {
            materialResumeDao.insertBatch(mrWithoutDupList);
        }
        resp.setFailedList(failedList);
        resp.setRetCode(failedList.size() > 0 ?
                ReturnCodes.HTTP_IMPORT_PART_FAIL.getRetCode() : ReturnCodes.HTTP_SUCCESS.getRetCode());
        resp.setRetMessage(failedList.size() > 0 ? "导入状态变更信息部分成功" : "导入状态变更信息成功");
        return resp;
    }

    @Override
    public void updateMaterialStatus(String material, String region, String targetStatus) {

    }

    @Override
    public ImportResp importDetails(String fileName) {
        String filePath = fileName;
        return excelImportService.excelFile(filePath, 2, new ExcelImportCallBack() {
            @Override
            public Collection<RowError> checkRow(String[] record) {
                return checkRecordValid(record);
            }

            @Override
            public boolean persistRowToDb(String[] record) {
                MaterialStatusImportDto materialStatusImportDto = covertToBean(record);
                return false;
//				try {
//					mocDetailDao.addDetail(mocDetail);
//					return true;
//				} catch (Exception e) {
//					return false;
//				}
            }

            @Override
            public ImportResp partFailure(ImportResp resp) {
//				resp.setRetMessage("导入状态变更记录数据部分失败，总数=" + resp.getTotal() + ",失败总数=" + resp.getFailedTotal());
                resp.setRetCode(ReturnCodes.HTTP_SUCCESS.getRetCode());
                return resp;
            }

            @Override
            public ImportResp allSuccess(ImportResp resp) {
                resp.setRetMessage("导入状态变更录数据全部成功，总数=" + resp.getTotal());
                return resp;
            }

            @Override
            public List<Map> convertFailList(List<String[]> failRecords) {
                List<Map> list = new ArrayList<>();
                int sort = 1;
                for (String[] failRecord : failRecords) {
                    Map item = new HashMap();
                    item.put("sort", sort);
                    item.put("material", failRecord[0]);
                    item.put("regionOne", failRecord[1]);
                    item.put("regionTwo", failRecord[2]);
                    item.put("regionThree", failRecord[3]);
                    item.put("changeTime", failRecord[4]);
                    list.add(item);
                    sort++;
                }
                return list;
            }

        });
    }

    /**
     * 转换数据为入库数据
     *
     * @param record 数据记录
     * @return 入库数据
     */
    private MaterialStatusImportDto covertToBean(String[] record) {
        MaterialStatusImportDto materialStatusImportDto = new MaterialStatusImportDto();
        materialStatusImportDto.setMaterial(record[0].trim());
        materialStatusImportDto.setRegionOne(record[1].trim());
        materialStatusImportDto.setRegionTwo(record[2].trim());
        materialStatusImportDto.setRegionThree(record[3].trim());
        materialStatusImportDto.setChangeTime(record[4].trim());
        return materialStatusImportDto;

    }

    /**
     * 校验参数合法性
     *
     * @param record 导入数据
     * @return 参数合法性
     */
    private Collection<RowError> checkRecordValid(String[] record) {
        List<RowError> rowErrors = new ArrayList<>();
        if (StringUtils.isEmpty(record[0].trim())) {
            addRowError("物料号不能为空", rowErrors);
        } else {
            if (record[0].trim().length() > 20) {
                addRowError("物料号长度不能超过20", rowErrors);
            }
        }
//		if (StringUtils.isEmpty(record[1].trim())) {
//			addRowError("域不能为空", rowErrors);
//		} else {
//			if (record[1].trim().length() > 20) {
//				addRowError("域长度不能超过20", rowErrors);
//			}
//		}
//		if (StringUtils.isEmpty(record[2].trim())) {
//			addRowError("描述不能为空", rowErrors);
//		} else {
//			if (record[2].trim().length() > 100) {
//				addRowError("描述长度不能超过100", rowErrors);
//			}
//		}
//		if (StringUtils.isEmpty(record[3].trim())) {
//			addRowError("参数类型不能为空", rowErrors);
//		} else {
//			if (record[3].trim().length() > 100) {
//				addRowError("参数类型长度不能超过100", rowErrors);
//			}
//		}
//		if (StringUtils.isEmpty(record[4].trim())) {
//			addRowError("原参数不能为空", rowErrors);
//		} else {
//			if (record[4].trim().length() > 100) {
//				addRowError("原参数长度不能超过100", rowErrors);
//			}
//		}
//		if (StringUtils.isEmpty(record[5].trim())) {
//			addRowError("新参数不能为空", rowErrors);
//		} else {
//			String compatibility = record[4].trim();
//			if (!StringUtils.equals(compatibility, "兼容") && !StringUtils.equals(compatibility, "不兼容")) {
//				addRowError("兼容性字段不合法", rowErrors);
//			}
//			if (record[5].trim().length() > 100) {
//				addRowError("新参数长度不能超过100", rowErrors);
//			}
//		}if(record[6].trim().length()>200)

//        {
//            addRowError("修改说明长度不能超过100", rowErrors);
//        }

        return rowErrors;
    }

    /**
     * 添加错误行数据
     *
     * @param errorMessage 错误信息
     * @param rowErrors    错误行数据
     */
    private void addRowError(String errorMessage, List<RowError> rowErrors) {
        RowError rowError = new RowError(errorMessage);
        rowErrors.add(rowError);
    }

    /**
     * 创建MocDetail
     *
     * @param id       id
     * @param recordId moc record id
     * @param material 物料号
     * @param newValue 新参数值
     * @param region   作用域
     * @return 新MocDetail实体
     */
    private MocDetail createMD(String id, String recordId, String material, String newValue, String region) {
        MocDetail mocDetail = new MocDetail();
        mocDetail.setId(id);
        mocDetail.setRecordId(recordId);
        mocDetail.setMaterial(material);
        mocDetail.setNewValue(newValue);
        mocDetail.setOldValue("-");
        mocDetail.setParam("状态");
        mocDetail.setRegion(region);
        return mocDetail;
    }

    /**
     * 创建MaterialResume
     *
     * @param mocDetail     变更详情
     * @param user         操作用户
     * @param operateTime  操作时间
     * @return 新MaterialResume实体
     */
    private MaterialResume createMR(MocDetail mocDetail, String user, String operateTime) {
        MaterialResume materialResume = new MaterialResume();
        materialResume.setId(SnowFlake.nextIdStr());
        materialResume.setSourceId(mocDetail.getId());
        materialResume.setMaterialNo(mocDetail.getMaterial());
        materialResume.setOperateUser(user);
        materialResume.setOperateType(MaterialResumeTypeEnum.STATUS_CHANGE.getValue());
        materialResume.setOperateTime(StringUtils.isNotEmpty(operateTime) ? operateTime : TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS));
        materialResume.setContent("物料状态改" + mocDetail.getNewValue());
        materialResume.setRegion(mocDetail.getRegion());
        return materialResume;
    }
}
